from random import randint, choice
from django.shortcuts import render
from rest_framework import status
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework_simplejwt import authentication
from django_filters import rest_framework as filters
from apps.app.utils.pager import Pagination
from django.contrib.auth.models import User, Group
from apps.app.utils.serializers import *
from apps.app.models import *
from django.db.models import Q,FilteredRelation
import datetime

# Create your views here.
# 系统用户
class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    filterset_fields = ('username', 'email')
    #filter_class = MyFilter
    #queryset.filter(username__contains('111'))

    serializer_class = UserSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)

# 用户组
class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all().order_by('-id')
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)

# 菜单
class MenuViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    #permission_classes = [permissions.IsAuthenticated]
    #authentication_classes = (authentication.JWTAuthentication,)
    queryset = MenuModel.objects.all().order_by('-id')

    filter_backends = (filters.DjangoFilterBackend,)
    filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = MenuSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    #自定义方法-根据pid获取数据
    @action(methods=['get'], detail=False, url_path=r'pid/(?P<pid>\d+)')
    def myQuery(self, request, pid, *args, **kwargs):
        self.serializer_class = MenuTreeSerializer
        queryset = MenuModel.objects.all().filter(pid=pid)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    #自定义方法-获取树型数据
    @action(methods=['get'], detail=False, url_path=r'tree')
    def tree(self, request, *args, **kwargs):
        self.serializer_class = MenuTreeSerializer
        queryset = MenuModel.objects.all()
        serializer = self.get_serializer(queryset, many=True)
        dTreeList = CommonSerializer.xTree(serializer.data)
        return Response(dTreeList, status=status.HTTP_200_OK)
    

# 部门
class DeptViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = DeptModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = DeptSerializer
    pagination_class = Pagination

    #自定义方法-获取树型数据
    @action(methods=['get'], detail=False, url_path=r'tree')
    def tree(self, request, *args, **kwargs):
        self.serializer_class = DeptTreeSerializer
        queryset = DeptModel.objects.all()
        serializer = self.get_serializer(queryset, many=True)
        dTreeList = CommonSerializer.xTree(serializer.data)
        return Response(dTreeList, status=status.HTTP_200_OK)

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)


# 角色
class RoleViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = RoleModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = RoleSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)


# 人员管理
class StaffViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    #permission_classes = [permissions.IsAuthenticated]
    #authentication_classes = (authentication.JWTAuthentication,)
    queryset = StaffModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = StaffSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    #自定义方法-根据pid获取数据
    @action(methods=['get'], detail=False, url_path=r'mock')
    def mock(self, request, *args, **kwargs):

        nameList = ['AA', '阿一', '店小二', '李四','张三','王五','陈六','小七','阿八','阿九','示例用户']
        deptList = ['办公室','行政部','后勤部']
        mobileList = ['腾讯QQ','微信','WPS','检查工具','远程连接','office','foxmail']
        addressList = ['1.10.3','17.5.54.1','11.11.12','v1','2010','2020v3']
        jobList = ['岗位1','技术员','办公室人员','营销中心','监管中心']
        for i in range(1, 10):
            data = {}
            ii = randint(1000, 10000)
            data['name'] = choice(nameList) + str(ii)
            data['dept_id'] = choice(deptList) + str(ii)
            data['idcard'] = randint(10, 100) + randint(1000, 10000) + randint(1000, 10000) + randint(1000, 10000) + randint(1000, 10000)
            data['mobile'] = 1 + randint(10, 100) + randint(1000, 10000) + randint(1000, 10000)
            data['address'] = choice(addressList)
            data['job'] = choice(jobList)
            data['entry_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            data['leave_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            # 获取序列化器
            serializer = self.get_serializer(data=data)
            # 验证
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response(status=status.HTTP_200_OK)
    

# 终端管理
class DeviceViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    #permission_classes = [permissions.IsAuthenticated]
    #authentication_classes = (authentication.JWTAuthentication,)
    queryset = DeviceModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = DeviceSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    #自定义方法-根据pid获取数据
    @action(methods=['get'], detail=False, url_path=r'mock')
    def mock(self, request, *args, **kwargs):

        nameList = ['阿一', '店小二', '李四','张三','王五','陈六','小七','阿八','阿九','示例用户']
        macList = ['aa:bb:cc:dd:ee', 'aa:bb:cc:dd:e1', 'a1:b2:cc:dd:e3']
        deptList = ['办公室','行政部','后勤部']
        softList = ['腾讯QQ','微信','WPS','检查工具','远程连接','office','foxmail']
        ipList = ['1.10.3.1','17.5.54.1','11.11.12.2']
        sysList = ['win','linux','mac','ous','qilin']
        authList = ['正版','盗版']
        for i in range(1, 100):
            data = {}
            data['dept_id'] = choice(deptList)
            data['mac'] = choice(macList)
            data['ip'] = choice(ipList)
            data['sys'] = choice(sysList)
            data['staff_id'] = choice(nameList) + str(randint(1000, 10000))

            # 获取序列化器
            serializer = self.get_serializer(data=data)
            # 验证
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response(status=status.HTTP_200_OK)
    

# 终端管理
class DeviceCheckViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    #permission_classes = [permissions.IsAuthenticated]
    #authentication_classes = (authentication.JWTAuthentication,)
    queryset = DeviceCheckModel.objects.all() #.order_by('id')
    # queryset = DeviceCheckModel.objects.annotate(b = FilteredRelation('DeviceModel')).all()
    #queryset = DeviceCheckModel.objects.extra()

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = DeviceCheckSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

# 终端管理
class DeviceCheckAllViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    #permission_classes = [permissions.IsAuthenticated]
    #authentication_classes = (authentication.JWTAuthentication,)
    queryset = DeviceModel.objects.all() #.order_by('id')
    # queryset = DeviceCheckModel.objects.annotate(b = FilteredRelation('DeviceModel')).all()
    #queryset = DeviceCheckModel.objects.extra()

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = DeviceCheckAllSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
# 终端管理
class DeviceSoftViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    #permission_classes = [permissions.IsAuthenticated]
    #authentication_classes = (authentication.JWTAuthentication,)
    queryset = DeviceSoftModel.objects.all().order_by('id') #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)

    serializer_class = DeviceSoftSerializer
    pagination_class = Pagination

    def list(self, request):
        userId = self.request.query_params.get('userId')
        if int(userId) > 0:
            queryset = DeviceSoftModel.objects.filter(user_id=userId).order_by('-id')
        else:
            queryset = DeviceSoftModel.objects.all().order_by('-id')

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    #自定义方法-根据pid获取数据
    @action(methods=['get'], detail=False, url_path=r'mock')
    def mock(self, request, *args, **kwargs):

        nameList = ['', '阿一', '店小二', '李四','张三','王五','陈六','小七','阿八','阿九','示例用户']
        deptList = ['办公室','行政部','后勤部']
        softList = ['腾讯QQ','微信','WPS','检查工具','远程连接','office','foxmail']
        verList = ['1.10.3','17.5.54.1','11.11.12','v1','2010','2020v3']
        typeList = ['操作系统','其他','办公软件','检查工具','安全工具']
        authList = ['正版','盗版']
        for i in range(1, 100):
            data = {}
            userId = randint(1, 9)
            data['user_id'] = userId
            data['username'] = nameList[userId]
            data['dept_id'] = choice(deptList)
            data['soft_name'] = choice(softList)
            data['soft_version'] = choice(verList)
            data['soft_type'] = choice(typeList)
            data['is_auth'] = choice(authList)

            # 获取序列化器
            serializer = self.get_serializer(data=data)
            # 验证
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response(status=status.HTTP_200_OK)
    

# 合同管理
class AgreementViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = AgreementModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = AgreementSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

# 授权管理
class AuthViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = AuthModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = AuthSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

# 领导小组
class LeaderViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = LeaderModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = LeaderSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

# 资产申请记录表
class ApplyViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = ApplyModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = ApplySerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

# 采购计划表
class PurchaseViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = PurchaseModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = PurchaseSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

# 相关制度
class DutyViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = DutyModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = DutySerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

# 资产列表
class HardwareViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = HardwareModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = HardwareSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

# 采购管理
class HardwarePurchaseViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = HardwarePurchaseModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = HardwarePurchaseSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

# 供应商管理
class SupplierViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = SupplierModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = SupplierSerializer
    pagination_class = Pagination

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

# 字典管理
class DictViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    #permission_classes = [permissions.IsAuthenticated]
    #authentication_classes = (authentication.JWTAuthentication,)
    queryset = DictModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)
    #filterset_fields = ('name',)
    #filter_class = MyFilter

    serializer_class = DictSerializer
    pagination_class = Pagination

    #自定义方法-根据pid获取数据
    @action(methods=['get'], detail=False, url_path=r'list')
    def myList(self, request):
        querysetDict = DictModel.objects.all()
        self.serializer_class = DictAllSerializer
        serializer = self.get_serializer(querysetDict, many=True)
        dictList = DictAllSerializer.toDict(serializer.data)
        return Response(dictList, status=status.HTTP_200_OK)

    #自定义方法-根据pid获取数据
    @action(methods=['get'], detail=False, url_path=r'one')
    def one(self, request):
        type = self.request.query_params.get('type')
        querysetDict = DictDataModel.objects.filter(type=type).all()
        self.serializer_class = DictDataSerializer
        serializer = self.get_serializer(querysetDict, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)
        

# 字典值管理
class DictDataViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = (authentication.JWTAuthentication,)
    queryset = DictDataModel.objects.all() #.order_by('id')

    filter_backends = (filters.DjangoFilterBackend,)

    serializer_class = DictDataSerializer
    pagination_class = Pagination

    #自定义方法-根据pid获取数据
    # @action(methods=['get'], detail=False, url_path=r'(?P<type>\w+)')
    def list(self, request):
        dictId = self.request.query_params.get('id')
        print(dictId)
        querysetDict = DictModel.objects.filter(id=dictId).first()
        type = querysetDict.type
        self.serializer_class = DictDataSerializer
        queryset = DictDataModel.objects.all().filter(type=type)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def create(self, request, *args, **kwargs):
        data = request.data
        dictId = data['type']
        queryset = DictModel.objects.filter(id=dictId).first()
        type = queryset.type
        request.data['type'] = type
    
        # 获取序列化器
        serializer = self.get_serializer(data=request.data)
        # 验证
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=status.HTTP_200_OK)

    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return Response(serializer.data, status=status.HTTP_200_OK)